<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Redis;

class ApiCheckSign
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (config('app.api_check_sign')) {
            //验证接口签名
            if (!$request->hasHeader('sign') || !$request->hasHeader('nonce') || !$request->hasHeader('timestamp') || strlen($request->header('nonce')) >= 100) {
                abort(401, 'Unauthorized');
            }
            //签名生命期判断（允许5分钟时间差）
//            if (time() - $request->get('timestamp') > 60 * 5) {
//                return failReturn(403, 'time out');
//            }
            $nonce_str = $request->header('nonce');
            //判断随机字符串是否已经被使用，一个随机字符串只允许使用一次
            if (redis::exists($nonce_str)) {
                abort(401, 'Invalid nonce');
            }
            Redis::setex($nonce_str, 5 * 60, '1');//5分钟过期
            $buff = "";
            $params = $request->all();



            $params['nonce'] = $request->header('nonce');
            $params['timestamp'] = $request->header('timestamp');
            ksort($params);
            foreach ($params as $k => $v) {
                $buff .= $k . "=" . trim($v) . "&";
            }

            $string = strlen($buff) > 0 ? substr($buff, 0, strlen($buff) - 1) : '';
            $key = 'x8hx8ypdii9rtwmn';//需要与客户端一致
            $string .= '&key=' . $key;
            $sign = hash_hmac('sha1', $string, $key);
            if ($sign != $request->header('sign')) {
                abort(401, 'Sign error');
            }
        }
        return $next($request);
    }
}
